package com.example.mybatis.service.impl;

import com.example.mybatis.business.IExcelBusiness;
import com.example.mybatis.business.IUserBusiness;
import com.example.mybatis.form.UserForm;
import com.example.mybatis.model.*;
import com.example.mybatis.service.IExcelService;
import com.example.mybatis.utils.ExcelReadWriteUtil;
import com.example.mybatis.utils.ReadWorkbookXmlUtil;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;



@Service("excelService")
public class ExcelService implements IExcelService {


    private WorkbookInfo exportWorkbook = null;
    private WorkbookInfo importWorkbook = null;

    @Autowired
    private IUserBusiness userBusiness;

    @Autowired
    private IExcelBusiness excelBusiness;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
    private static final Logger logger = LoggerFactory.getLogger(ExcelService.class);

    private String exportFilePath = "src/main/resources/excelConfig/exportExample.xml";

    private String importFilePath = "src/main/resources/excelConfig/importExample.xml";



    @Override
    public void exportSheet(String sheetName, Integer page,Integer pageSize,HttpServletResponse response) {
        logger.info("sheetName={}",sheetName);
        Date now = new Date();
        String dateTime = sdf.format(now);
        //设置文件名
        String fileName = sheetName+dateTime+".xlsx";
        try {
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));

        } catch (UnsupportedEncodingException e) {
            logger.error("encode fileName failed!",e);
            throw new RuntimeException("encode fileName failed,caused by: "+e.getMessage());
        }
        if(exportWorkbook==null){
            SAXReader saxReader = new SAXReader();
            //读取导出xml配置
            exportWorkbook = ReadWorkbookXmlUtil.readWorkbookXml(saxReader,exportFilePath);
        }
        SheetInfo sheetInfo = exportWorkbook.getSheetInfoMap().get(sheetName);
        Map<String,SheetInfo> sheetInfoMap = new HashMap<>();
        sheetInfoMap.put(sheetName,sheetInfo);
        Map<String,List<?>> dataMap = new HashMap<>();
        //计算查询起始索引
        int startIndex = (page-1)*pageSize+1;
        try {
            List<UserTO> userTOList = userBusiness.selectAllUser(startIndex,pageSize);
            dataMap.put(sheetName,userTOList);
            //从HttpServletResponse对象中获取输出流
            OutputStream os = response.getOutputStream();
            ExcelReadWriteUtil.writeExcel(sheetInfoMap,dataMap,os);
        } catch (Exception e) {
            logger.error("exportSheet failed!",e);
            throw new RuntimeException("exportSheet failed, caused by: "+e.getMessage());

        }

    }

    @Override
    public void exportSearchSheet(UserForm form, SheetInfo sheetInfo, HttpServletResponse response)throws Exception {
        String sheetName = sheetInfo.getName();
        Date now = new Date();
        String dateTime = sdf.format(now);
        String fileName = sheetName+dateTime+".xlsx";
        response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
        List<UserTO> userList = userBusiness.searchUsers(form);
        OutputStream os = response.getOutputStream();
            //调用工具类写Excel
        ExcelReadWriteUtil.writeSingleExcel(sheetInfo,userList,os);
        logger.info("export single excel sheet success!");



    }

    @Override
    public ServiceResponse<String> importExcel(File file, boolean isExcel2003) throws Exception{
        ServiceResponse<String> response = new ServiceResponse<>();
        if(importWorkbook==null){
            SAXReader saxReader = new SAXReader();
            //读取导入xml配置
            importWorkbook = ReadWorkbookXmlUtil.readWorkbookXml(saxReader,importFilePath);
        }
        if(importWorkbook==null){
            throw new NullPointerException("importWorkbook instance cannot be null");
        }
        Map<String,SheetInfo> sheetInfoMap = importWorkbook.getSheetInfoMap();
        //调用工具类解析出数据
        Map<String,List<?>> dataMap = null;
        try {
            dataMap = ExcelReadWriteUtil.readExcel(sheetInfoMap,file,isExcel2003);
        } catch (Exception e) {
            logger.error("readExcel failed",e);
            response.setStatus(500);
            response.setMessage("Inner Server Error,caused by: "+e.getMessage());
            return response;
        }

        String importMsg = "";
        if(dataMap!=null && dataMap.size()>0){
                importMsg = excelBusiness.importExcelResolvedData(dataMap);
        }
        response.setStatus(200);
        response.setMessage("ok");
        response.setMessage(importMsg);

        return response;
    }
}
